<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="decoration-circle circle-1"></div>
      <div class="decoration-circle circle-2"></div>
      <div class="decoration-circle circle-3"></div>
      <div class="decoration-grid"></div>
    </div>
    
    <!-- 登录卡片 -->
    <div class="login-card" :class="{ 'shake': loginError }">
      <!-- 头部 -->
      <div class="login-header">
        <div class="logo-section">
          <div class="logo-icon">
            <el-icon><Folder /></el-icon>
          </div>
          <div class="logo-text">
            <h1>文件管理系统</h1>
            <p>安全、高效的文件管理平台</p>
          </div>
        </div>
      </div>
      
      <!-- 表单区域 -->
      <div class="login-form-container">
        <div class="form-header">
          <h2>欢迎回来</h2>
          <p>请输入您的账户信息以继续</p>
        </div>
        
        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-alert">
          <el-icon class="error-icon"><WarningFilled /></el-icon>
          <span>{{ errorMessage }}</span>
        </div>
        
        <el-form 
          :model="loginForm" 
          :rules="loginRules" 
          ref="loginFormRef" 
          class="login-form"
          @keyup.enter="handleLogin"
        >
          <el-form-item prop="username">
            <div class="input-wrapper">
              <label class="input-label">用户名</label>
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                size="large"
                class="custom-input"
                :class="{ 'input-error': usernameError }"
                @focus="clearErrors"
                @input="clearErrors"
                autocomplete="username"
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </div>
          </el-form-item>
          
          <el-form-item prop="password">
            <div class="input-wrapper">
              <label class="input-label">密码</label>
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                class="custom-input"
                :class="{ 'input-error': passwordError }"
                @focus="clearErrors"
                @input="clearErrors"
                @keyup.enter="handleLogin"
                show-password
                autocomplete="current-password"
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </div>
          </el-form-item>
          
          <!-- 记住密码和忘记密码 -->
          <div class="form-options">
            <el-checkbox v-model="rememberMe" class="remember-checkbox">
              记住密码
            </el-checkbox>
            <a href="#" class="forgot-password" @click.prevent="handleForgotPassword">
              忘记密码？
            </a>
          </div>
          
          <el-form-item class="login-button-item">
            <el-button
              type="primary"
              @click="handleLogin"
              :loading="loading"
              size="large"
              class="login-button"
              :disabled="!isFormValid"
            >
              <span v-if="!loading">登录</span>
              <span v-else>登录中...</span>
            </el-button>
          </el-form-item>
        </el-form>
        
        <!-- 快速登录提示 -->
        <div class="quick-login-tip">
          <el-divider>
            <span class="divider-text">快速登录</span>
          </el-divider>
          <div class="demo-accounts">
            <el-button 
              text 
              type="primary" 
              size="small" 
              @click="fillDemoAccount('admin')"
              class="demo-btn"
            >
              管理员账户
            </el-button>
            <el-button 
              text 
              type="primary" 
              size="small" 
              @click="fillDemoAccount('user')"
              class="demo-btn"
            >
              普通用户
            </el-button>
          </div>
        </div>
        
        <!-- 底部信息 -->
        <div class="login-footer">
          <div class="footer-links">
            <a href="#" class="footer-link" @click.prevent="handleContactAdmin">
              <el-icon><Service /></el-icon>
              联系管理员
            </a>
            <a href="#" class="footer-link" @click.prevent="handleHelp">
              <el-icon><QuestionFilled /></el-icon>
              使用帮助
            </a>
          </div>
          <div class="footer-info">
            <p>&copy; 2024 文件管理系统. 保留所有权利.</p>
            <p class="version-info">版本 v1.0.0</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载遮罩 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner">
        <el-icon class="rotating"><Loading /></el-icon>
        <p>正在登录...</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  Lock, 
  Folder, 
  WarningFilled, 
  Service, 
  QuestionFilled, 
  Loading 
} from '@element-plus/icons-vue'

const router = useRouter()
const authStore = useAuthStore()

const loginFormRef = ref()
const loading = ref(false)
const rememberMe = ref(false)
const loginError = ref(false)
const errorMessage = ref('')
const usernameError = ref(false)
const passwordError = ref(false)
const loginAttempts = ref(0)
const maxAttempts = 5

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '用户名长度不能少于2位', trigger: 'blur' },
    { max: 50, message: '用户名长度不能超过50位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    { max: 100, message: '密码长度不能超过100位', trigger: 'blur' }
  ]
}

// 计算表单是否有效
const isFormValid = computed(() => {
  return loginForm.username.length >= 2 && 
         loginForm.password.length >= 6 && 
         loginAttempts.value < maxAttempts
})

// 监听登录尝试次数
watch(loginAttempts, (newVal) => {
  if (newVal >= maxAttempts) {
    errorMessage.value = `登录失败次数过多，请稍后再试`
    setTimeout(() => {
      loginAttempts.value = 0
      errorMessage.value = ''
    }, 300000) // 5分钟后重置
  }
})

// 从本地存储加载记住的用户信息
onMounted(() => {
  const savedUsername = localStorage.getItem('rememberedUsername')
  const savedPassword = localStorage.getItem('rememberedPassword')
  if (savedUsername && savedPassword) {
    loginForm.username = savedUsername
    loginForm.password = savedPassword
    rememberMe.value = true
  }
  
  // 检查是否有保存的登录失败次数
  const savedAttempts = localStorage.getItem('loginAttempts')
  if (savedAttempts) {
    loginAttempts.value = parseInt(savedAttempts)
  }
})

// 清除错误状态
const clearErrors = () => {
  errorMessage.value = ''
  usernameError.value = false
  passwordError.value = false
  loginError.value = false
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value || loginAttempts.value >= maxAttempts) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      clearErrors()
      
      try {
        const result = await authStore.login(loginForm)
        if (result.success) {
          // 处理记住密码
          if (rememberMe.value) {
            localStorage.setItem('rememberedUsername', loginForm.username)
            localStorage.setItem('rememberedPassword', loginForm.password)
          } else {
            localStorage.removeItem('rememberedUsername')
            localStorage.removeItem('rememberedPassword')
          }
          
          // 重置登录尝试次数
          loginAttempts.value = 0
          localStorage.removeItem('loginAttempts')
          
          ElMessage.success({
            message: '登录成功，欢迎回来！',
            type: 'success',
            duration: 2000
          })
          
          // 延迟跳转以显示成功消息
          setTimeout(() => {
            router.push('/')
          }, 500)
        } else {
          handleLoginError(result.message || '登录失败，请检查用户名和密码')
        }
      } catch (error) {
        console.error('Login error:', error)
        handleLoginError('网络连接失败，请检查网络后重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 处理登录错误
const handleLoginError = (message) => {
  loginAttempts.value++
  localStorage.setItem('loginAttempts', loginAttempts.value.toString())
  
  errorMessage.value = message
  loginError.value = true
  usernameError.value = true
  passwordError.value = true
  
  // 震动效果
  setTimeout(() => {
    loginError.value = false
  }, 600)
  
  // 清空密码
  loginForm.password = ''
  
  ElMessage.error({
    message: `${message} (${loginAttempts.value}/${maxAttempts})`,
    duration: 3000
  })
}

// 填充演示账户
const fillDemoAccount = (type) => {
  clearErrors()
  if (type === 'admin') {
    loginForm.username = 'admin'
    loginForm.password = 'admin123'
  } else {
    loginForm.username = 'user'
    loginForm.password = 'user123'
  }
  rememberMe.value = false
}

// 处理忘记密码
const handleForgotPassword = () => {
  ElMessageBox.alert(
    '请联系系统管理员重置密码，或发送邮件至 admin@example.com',
    '忘记密码',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  )
}

// 联系管理员
const handleContactAdmin = () => {
  ElMessageBox.alert(
    '管理员联系方式：\n电话：400-123-4567\n邮箱：admin@example.com\n工作时间：周一至周五 9:00-18:00',
    '联系管理员',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  )
}

// 使用帮助
const handleHelp = () => {
  ElMessageBox.alert(
    '使用帮助：\n1. 输入正确的用户名和密码\n2. 可选择记住密码功能\n3. 如遇问题请联系管理员\n4. 支持键盘快捷键 Enter 登录',
    '使用帮助',
    {
      confirmButtonText: '确定',
      type: 'info'
    }
  )
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  padding: var(--spacing-lg);
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 1;
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 8s ease-in-out infinite;
}

.decoration-grid {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    linear-gradient(rgba(255, 255, 255, 0.03) 1px, transparent 1px),
    linear-gradient(90deg, rgba(255, 255, 255, 0.03) 1px, transparent 1px);
  background-size: 50px 50px;
  animation: gridMove 20s linear infinite;
}

.circle-1 {
  width: 300px;
  height: 300px;
  top: -150px;
  left: -150px;
  animation-delay: 0s;
}

.circle-2 {
  width: 200px;
  height: 200px;
  top: 20%;
  right: -100px;
  animation-delay: 3s;
}

.circle-3 {
  width: 150px;
  height: 150px;
  bottom: -75px;
  left: 30%;
  animation-delay: 6s;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  33% {
    transform: translateY(-30px) rotate(120deg);
  }
  66% {
    transform: translateY(15px) rotate(240deg);
  }
}

@keyframes gridMove {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(50px, 50px);
  }
}

/* 登录卡片 */
.login-card {
  width: 100%;
  max-width: 480px;
  background: var(--bg-primary);
  border-radius: var(--radius-xl);
  box-shadow: var(--shadow-2xl);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  overflow: hidden;
  position: relative;
  z-index: 2;
  animation: slideUp 0.8s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

.login-card.shake {
  animation: shake 0.6s ease-in-out;
}

/* 头部样式 */
.login-header {
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  color: var(--text-inverse);
  padding: var(--spacing-xl);
  text-align: center;
  position: relative;
}

.login-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="dots" width="20" height="20" patternUnits="userSpaceOnUse"><circle cx="10" cy="10" r="1" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23dots)"/></svg>');
  pointer-events: none;
}

.logo-section {
  position: relative;
  z-index: 1;
}

.logo-icon {
  width: 64px;
  height: 64px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto var(--spacing-md);
  font-size: 2rem;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.logo-text h1 {
  font-size: 1.75rem;
  font-weight: 700;
  margin: 0 0 var(--spacing-xs) 0;
  line-height: 1.2;
}

.logo-text p {
  font-size: 0.875rem;
  opacity: 0.9;
  margin: 0;
  font-weight: 400;
}

/* 表单容器 */
.login-form-container {
  padding: var(--spacing-xl);
}

.form-header {
  text-align: center;
  margin-bottom: var(--spacing-xl);
}

.form-header h2 {
  font-size: 1.5rem;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-xs) 0;
  line-height: 1.2;
}

.form-header p {
  color: var(--text-secondary);
  font-size: 0.875rem;
  margin: 0;
}

/* 表单样式 */
.login-form {
  margin-bottom: var(--spacing-lg);
}

.input-wrapper {
  margin-bottom: var(--spacing-lg);
}

.input-label {
  display: block;
  font-size: 0.875rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
}

.custom-input :deep(.el-input__wrapper) {
  border-radius: var(--radius-lg);
  border: 2px solid var(--border-light);
  box-shadow: none;
  transition: all var(--transition-normal);
  padding: var(--spacing-md) var(--spacing-lg);
  background: var(--bg-secondary);
}

.custom-input :deep(.el-input__wrapper:hover) {
  border-color: var(--primary-color);
  background: var(--bg-primary);
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
  background: var(--bg-primary);
}

.custom-input :deep(.el-input__inner) {
  font-size: 1rem;
  color: var(--text-primary);
  font-weight: 500;
}

.custom-input :deep(.el-input__prefix) {
  color: var(--text-secondary);
}

.custom-input :deep(.el-input__suffix) {
  color: var(--text-secondary);
}

.custom-input.input-error :deep(.el-input__wrapper) {
  border-color: var(--danger-color) !important;
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1) !important;
}

/* 错误提示 */
.error-alert {
  background: rgba(239, 68, 68, 0.1);
  border: 1px solid rgba(239, 68, 68, 0.2);
  border-radius: var(--radius-md);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  display: flex;
  align-items: center;
  gap: var(--spacing-sm);
  color: var(--danger-color);
  font-size: 0.875rem;
  animation: slideDown 0.3s ease-out;
}

.error-icon {
  font-size: 1.125rem;
  flex-shrink: 0;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 表单选项 */
.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
}

.remember-checkbox {
  font-size: 0.875rem;
}

.remember-checkbox :deep(.el-checkbox__label) {
  color: var(--text-secondary);
  font-weight: 500;
}

.forgot-password {
  color: var(--primary-color);
  text-decoration: none;
  font-size: 0.875rem;
  font-weight: 500;
  transition: all var(--transition-normal);
}

.forgot-password:hover {
  color: var(--secondary-color);
  text-decoration: underline;
}

/* 登录按钮 */
.login-button-item {
  margin-bottom: 0;
}

.login-button {
  width: 100%;
  height: 56px;
  font-size: 1rem;
  font-weight: 600;
  border-radius: var(--radius-lg);
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  border: none;
  transition: all var(--transition-normal);
  position: relative;
  overflow: hidden;
}

.login-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.login-button:hover::before {
  left: 100%;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-xl);
}

.login-button:active {
  transform: translateY(0);
}

/* 底部信息 */
.login-footer {
  border-top: 1px solid var(--border-light);
  padding-top: var(--spacing-lg);
  text-align: center;
}

.footer-links {
  display: flex;
  justify-content: center;
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-md);
}

.footer-link {
  color: var(--primary-color);
  text-decoration: none;
  font-size: 0.875rem;
  font-weight: 500;
  transition: all var(--transition-normal);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.footer-link:hover {
  color: var(--secondary-color);
  text-decoration: underline;
  transform: translateY(-1px);
}

.footer-link .el-icon {
  font-size: 1rem;
}

.footer-info p {
  color: var(--text-tertiary);
  font-size: 0.75rem;
  margin: 0;
}

.version-info {
  margin-top: var(--spacing-xs) !important;
  opacity: 0.7;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .login-container {
    padding: var(--spacing-md);
  }
  
  .login-card {
    max-width: 100%;
  }
  
  .login-header,
  .login-form-container {
    padding: var(--spacing-lg);
  }
  
  .logo-text h1 {
    font-size: 1.5rem;
  }
  
  .form-header h2 {
    font-size: 1.25rem;
  }
  
  .footer-links {
    flex-direction: column;
    gap: var(--spacing-sm);
  }
}

@media (max-width: 480px) {
  .circle-1,
  .circle-2,
  .circle-3 {
    display: none;
  }
  
  .login-header,
  .login-form-container {
    padding: var(--spacing-md);
  }
  
  .logo-icon {
    width: 48px;
    height: 48px;
    font-size: 1.5rem;
  }
}

/* 加载状态 */
.login-button.is-loading {
  pointer-events: none;
}

.login-button.is-loading::before {
  display: none;
}

/* 快速登录 */
.quick-login-tip {
  margin: var(--spacing-xl) 0;
}

.divider-text {
  color: var(--text-tertiary);
  font-size: 0.75rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.demo-accounts {
  display: flex;
  justify-content: center;
  gap: var(--spacing-md);
  margin-top: var(--spacing-md);
}

.demo-btn {
  font-size: 0.75rem;
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-sm);
  transition: all var(--transition-normal);
}

.demo-btn:hover {
  background: rgba(99, 102, 241, 0.1);
  transform: translateY(-1px);
}

/* 加载遮罩 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  backdrop-filter: blur(5px);
}

.loading-spinner {
  background: var(--bg-primary);
  border-radius: var(--radius-lg);
  padding: var(--spacing-xl);
  text-align: center;
  box-shadow: var(--shadow-2xl);
  min-width: 200px;
}

.loading-spinner .el-icon {
  font-size: 2rem;
  color: var(--primary-color);
  margin-bottom: var(--spacing-md);
}

.loading-spinner p {
  color: var(--text-primary);
  font-size: 0.875rem;
  font-weight: 500;
  margin: 0;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.rotating {
  animation: rotating 1s linear infinite;
}

/* 表单验证错误样式 */
:deep(.el-form-item.is-error .el-input__wrapper) {
  border-color: var(--danger-color) !important;
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1) !important;
}

:deep(.el-form-item__error) {
  font-size: 0.75rem;
  margin-top: var(--spacing-xs);
}
</style>